package com.example.image.loader

import android.content.Context
import android.net.Uri
import android.widget.ImageView

import com.example.image.IImgLoader
import com.example.image.ImgOptions
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder
import com.facebook.drawee.view.SimpleDraweeView
import java.io.File

/**
 * Author: Jason Zhang
 * Date: 2025/1/10
 * Desc: Fresco图片加载器
 * 官方文档：https://frescolib.org/docs/
 */
class FrescoImgLoader: IImgLoader {
    override fun loadFileIntoImageView(
        ctx: Context,
        file: File,
        target: ImageView,
        option: ImgOptions
    ) {
        var imageUri = Uri.parse(file.absolutePath)
        loadImage(ctx, target, imageUri, option)
    }

    override fun loadUrlIntoImageView(
        ctx: Context,
        url: String,
        target: ImageView,
        option: ImgOptions
    ) {
        var imageUri = Uri.parse(url)
        loadImage(ctx, target, imageUri, option)
    }

    override fun loadResIntoImageView(
        ctx: Context,
        resId: Int,
        target: ImageView,
        option: ImgOptions
    ) {
        var imageUri = Uri.parse("res:///$resId")
        loadImage(ctx, target, imageUri, option)
    }

    override fun loadByteArrayIntoImageView(
        ctx: Context,
        byteArray: ByteArray,
        target: ImageView,
        option: ImgOptions
    ) {
        //暂时不支持
    }

    override fun loadUriIntoImageView(
        ctx: Context,
        uri: Uri,
        target: ImageView,
        option: ImgOptions
    ) {
        loadImage(ctx, target, uri, option)
    }

    private fun loadImage(ctx: Context, target: ImageView, imageUri: Uri, option: ImgOptions){
        //对象转换
        var simpleDrawView = target as SimpleDraweeView

        //设置控制器
        val controller = Fresco.newDraweeControllerBuilder()
            .setUri(imageUri) // 设置图片 URI
            .setAutoPlayAnimations(true) // 支持 GIF 动画
            .build()

        simpleDrawView.controller = controller

        //设置占位图参数
        val hierarchyBuilder = GenericDraweeHierarchyBuilder(ctx.resources)
        hierarchyBuilder.setPlaceholderImage(option.placeImage) // 占位图
        hierarchyBuilder.setFailureImage(option.errorImage) // 错误图

        simpleDrawView.hierarchy = hierarchyBuilder.build()

        //加载图片
        simpleDrawView.setImageURI(imageUri)

    }


}